package cn.jucheng.www.yizhudan;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.alibaba.fastjson.JSON;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jucheng.jclibs.socket.MyGlobal;
import cn.jucheng.jclibs.socket.WorkService;
import cn.jucheng.jclibs.tools.MyLog;
import cn.jucheng.jclibs.tools.SubStringUtils;
import cn.jucheng.www.yizhudan.base.FragmentTabAdapter;
import cn.jucheng.www.yizhudan.callback.MessageEvent;
import cn.jucheng.www.yizhudan.customcontrols.FitHeightButton;
import cn.jucheng.www.yizhudan.customcontrols.FitHeightEditText;
import cn.jucheng.www.yizhudan.customcontrols.FitHeightTextView;
import cn.jucheng.www.yizhudan.fragment.BloodrecordlistFragment;
import cn.jucheng.www.yizhudan.fragment.CurelistFragment;
import cn.jucheng.www.yizhudan.fragment.InjectionlistFragment;
import cn.jucheng.www.yizhudan.fragment.MedicalordersexecutiveFragment;
import cn.jucheng.www.yizhudan.fragment.TakemedicinelistFragment;
import cn.jucheng.www.yizhudan.fragment.TransfusionlistFragment;
import cn.jucheng.www.yizhudan.fragment.TransfusionrecordFragment;
import cn.jucheng.www.yizhudan.module.Medicines;
import cn.jucheng.www.yizhudan.module.MedicinesBean;
import cn.jucheng.www.yizhudan.module.UserMessage;
import cn.jucheng.www.yizhudan.utils.AppJsonFileReader;
import cn.jucheng.www.yizhudan.utils.DateUtils;
import cn.jucheng.www.yizhudan.view.TimeActivity;
import cn.jucheng.www.yizhudan.widget.HexadecimalConver;
import cn.jucheng.www.yizhudan.widget.MyGlobal1;
import cn.jucheng.www.yizhudan.widget.MyMessage;
import cn.jucheng.www.yizhudan.widget.MyShareUtils;
import cn.jucheng.www.yizhudan.zxing.activity.CaptureActivity;

/**
 * 主页
 * Created by w on 2017-11-21.
 */

public class PageActivity extends MyBaseActivity implements TextWatcher {

    /**
     * 护士姓名
     */
    @BindView(R.id.nurse_namae_text)
    FitHeightEditText nurseNamaeText;
    /**
     * 病人信息
     */
    @BindView(R.id.sickmessage_buton)
    FitHeightButton sickmessageButon;
    /**
     * 药物信息
     */
    @BindView(R.id.drugmessage_buton)
    FitHeightButton drugmessageButon;
    /**
     * 姓名
     */
    @BindView(R.id.name_text)
    FitHeightTextView nameText;
    /**
     * 性别
     */
    @BindView(R.id.sex_text)
    FitHeightTextView sexText;
    /**
     * 年龄
     */
    @BindView(R.id.age_text)
    FitHeightTextView ageText;
    /**
     * 住院号
     */
    @BindView(R.id.hospitalNumber_text)
    FitHeightTextView hospitalNumberText;
    /**
     * 床号
     */
    @BindView(R.id.bedNumber_text)
    FitHeightTextView bedNumberText;
    /**
     * 科室
     */
    @BindView(R.id.office_text)
    FitHeightTextView officeText;
    /**
     * 过敏史
     */
    @BindView(R.id.allergies_text)
    FitHeightTextView allergiesText;
    /**
     * 诊断
     */
    @BindView(R.id.diagnose_text)
    FitHeightTextView diagnoseText;
    /**
     * 设置
     */
    @BindView(R.id.set_buton)
    LinearLayout setButon;
    /**
     * 已连接
     */
    @BindView(R.id.connect_buton)
    ImageView connect;
    /**
     * 当前页码
     */
    static FitHeightTextView pageNumberAction;
    /**
     *
     */
    @BindView(R.id.main_tab_fragmentlayout)
    FrameLayout mainTabFragmentlayout;
    /**
     * 注射单
     */
    @BindView(R.id.injectionlist_buton)
    RadioButton injectionlistButon;
    /**
     * 治疗单
     */
    @BindView(R.id.curelist_buton)
    RadioButton curelistButon;
    /**
     * 服药单
     */
    @BindView(R.id.takemedicinelist_buton)
    RadioButton takemedicinelistButon;
    /**
     * 输液单
     */
    @BindView(R.id.transfusionlist_buton)
    RadioButton transfusionlistButon;
    /**
     * 医嘱执行单
     */
    @BindView(R.id.medicalordersexecutive_buton)
    RadioButton medicalordersexecutiveButon;
    /**
     * 输血观察记录单
     */
    @BindView(R.id.bloodrecordlist_buton)
    RadioButton bloodrecordlistButon;
    /**
     * 输液记录单
     */
    @BindView(R.id.transfusionrecord_buton)
    RadioButton transfusionrecordButon;

    @BindView(R.id.fragment_group)
    RadioGroup fragmentGroup;

    @BindView(R.id.connect_texView)
    FitHeightTextView connectText;

    FragmentTabAdapter fragmentAdapter;

    private List<Fragment> fragmentList = new ArrayList<Fragment>();
    public static MyShareUtils datas = null;//缓存数据

    Object object = new Object();
    String message_str = "";
    String befortime;
    String endtime;

    private MHandler mHandler;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_page);
        ButterKnife.bind(this);
        mHandler = new MHandler(this);
        WorkService.addHandler(mHandler);
        initData();
        initView();
        setErweimaMessage();
    }

    public void initData() {
        nurseNamaeText.addTextChangedListener(this);
        if (datas == null)
            datas = MyShareUtils.getInstances(this);

        pageNumberAction = (FitHeightTextView) findViewById(R.id.page_number_action);

    }

    /**
     * 加载选项卡
     */
    public void initView() {
        fragmentList.add(new InjectionlistFragment());
        fragmentList.add(new CurelistFragment());
        fragmentList.add(new TakemedicinelistFragment());
        fragmentList.add(new TransfusionlistFragment());
        fragmentList.add(new MedicalordersexecutiveFragment());
        fragmentList.add(new BloodrecordlistFragment());
        fragmentList.add(new TransfusionrecordFragment());
        fragmentAdapter = new FragmentTabAdapter(getSupportFragmentManager(), fragmentList, R.id.main_tab_fragmentlayout,
                fragmentGroup, 0);
    }

    @OnClick({R.id.sickmessage_buton, R.id.drugmessage_buton, R.id.set_buton, R.id.connect_buton})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.sickmessage_buton://病人信息
                Intent intent_patient = new Intent(PageActivity.this, CaptureActivity.class);
                intent_patient.putExtra("type", 1);
                startActivity(intent_patient);

                break;
            case R.id.drugmessage_buton://药物信息
                Intent intent_drug = new Intent(PageActivity.this, CaptureActivity.class);
                intent_drug.putExtra("type", 2);
                startActivity(intent_drug);
                break;
            case R.id.set_buton://设置
                Intent intents = new Intent(this, SettingsActivity.class);
                startActivity(intents);
                break;
            case R.id.connect_buton://已连接
                break;
        }
    }

    @Override
    protected void HandlerMessage(Message msg) {
        switch (msg.what) {
            case MyMessage.MLZ_BINGRENWANDAIXINXI://病人腕带信息
                object = msg.obj;
                message_str = (String) object;
                int action_lenth = 0;
                int end_lenth = 0;

                int name_lenth = Integer.parseInt(message_str.substring(52, 54), 16);
                end_lenth = 54 + (name_lenth * 2);
                action_lenth = end_lenth;
                String name = HexadecimalConver.toStringHex(message_str.substring(54, end_lenth));

                end_lenth = action_lenth + 2;
                int sex_lenth = Integer.parseInt(message_str.substring(action_lenth, end_lenth), 16);
                action_lenth = end_lenth;
                end_lenth = action_lenth + (sex_lenth * 2);
                String sex = HexadecimalConver.toStringHex(message_str.substring(action_lenth, end_lenth));

                action_lenth = end_lenth;
                end_lenth = action_lenth + 2;
                int age_lenth = Integer.parseInt(message_str.substring(action_lenth, end_lenth), 16);
                action_lenth = end_lenth;
                end_lenth = action_lenth + (age_lenth * 2);
                String age = HexadecimalConver.toStringHex(message_str.substring(action_lenth, end_lenth));

                action_lenth = end_lenth;
                end_lenth = action_lenth + 2;
                int hospitalNumber_lenth = Integer.parseInt(message_str.substring(action_lenth, end_lenth), 16);
                action_lenth = end_lenth;
                end_lenth = action_lenth + (hospitalNumber_lenth * 2);
                String hospitalNumber = HexadecimalConver.toStringHex(message_str.substring(action_lenth, end_lenth));

                action_lenth = end_lenth;
                end_lenth = action_lenth + 2;
                int bedNumber_lenth = Integer.parseInt(message_str.substring(action_lenth, end_lenth), 16);
                action_lenth = end_lenth;
                end_lenth = action_lenth + (bedNumber_lenth * 2);
                String bedNumber = HexadecimalConver.toStringHex(message_str.substring(action_lenth, end_lenth));

                action_lenth = end_lenth;
                end_lenth = action_lenth + 2;
                int office_lenth = Integer.parseInt(message_str.substring(action_lenth, end_lenth), 16);
                action_lenth = end_lenth;
                end_lenth = action_lenth + (office_lenth * 2);
                String office = HexadecimalConver.toStringHex(message_str.substring(action_lenth, end_lenth));

                action_lenth = end_lenth;
                end_lenth = action_lenth + 4;
                int allergies_lenth = Integer.parseInt(message_str.substring(action_lenth, end_lenth), 16);
                action_lenth = end_lenth;
                end_lenth = action_lenth + (allergies_lenth * 2);
                String allergies = HexadecimalConver.toStringHex(message_str.substring(action_lenth, end_lenth));

                action_lenth = end_lenth;
                end_lenth = action_lenth + 4;
                int diagnose_lenth = Integer.parseInt(message_str.substring(action_lenth, end_lenth), 16);
                action_lenth = end_lenth;
                end_lenth = action_lenth + (diagnose_lenth * 2);
                String diagnose = HexadecimalConver.toStringHex(message_str.substring(action_lenth, end_lenth));


                nameText.setText(name);
                sexText.setText(sex);
                ageText.setText(age);
                hospitalNumberText.setText(hospitalNumber);
                bedNumberText.setText(bedNumber);
                officeText.setText(office);
                allergiesText.setText(allergies);
                diagnoseText.setText(diagnose);

                break;
            case MyMessage.MLZ_BIAODANYOUXINXI://表单表头信息
                object = msg.obj;
                message_str = (String) object;
                String head_message = message_str.substring(52);
                datas.setData(MyGlobal1.ALLBIAODANMESSAGE, head_message);//存储表单头部信息
                EventBus.getDefault().post(new MessageEvent(head_message, 1));
                break;
            case MyMessage.MLZ_BIAODAN://学生填写的表单
                object = msg.obj;
                UserMessage.biaodan_message = (String) object;

                EventBus.getDefault().post(new MessageEvent(UserMessage.biaodan_message, 4));
                break;
            case MyMessage.MLZ_JIAOZHENGSHEBEISHIJIAN://校正时间
                Object z1 = msg.obj;
                String a1 = (String) z1;
                String atr = a1.substring(52);
                int nian = Integer
                        .parseInt(SubStringUtils.substring(a1,
                                52, 56), 16);
                int yue = Integer
                        .parseInt(SubStringUtils.substring(a1,
                                56, 58), 16);
                int ri = Integer
                        .parseInt(SubStringUtils.substring(a1,
                                58, 60), 16);
                int shi = Integer
                        .parseInt(SubStringUtils.substring(a1,
                                60, 62), 16);
                int fen = Integer
                        .parseInt(SubStringUtils.substring(a1,
                                62, 64), 16);
                int miao = Integer
                        .parseInt(SubStringUtils.substring(a1,
                                64, 66), 16);
                befortime = nian + "-" + yue + "-" + ri + " " + shi + ":" + fen + ":" + miao;

                String timename = DateUtils.getDefaultTimeZone();

                Intent intent = new Intent(PageActivity.this, TimeActivity.class);
                intent.putExtra("now_time",timename);//我的设备时区
                intent.putExtra("time",befortime);//服务时区
                startActivity(intent);

                MyLog.d("mwh","timename" + timename);

                break;
            case MyMessage.MLZ_GENGGAIYIZHUZHUANGTAI://签字成功
                Object z3 = msg.obj;
                String a3 = (String) z3;

                EventBus.getDefault().post(new MessageEvent(a3, 3));
                break;
            case MyMessage.MLZ_CLEARALL://清空所有信息
                //清空所有信息
                ClearMessage();
                break;
            default:
                break;
        }
    }

    @Override
    public void exc() {

    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        nurseNamaeText.getText().toString();
        datas.setData(MyGlobal1.NURSE_NAME, nurseNamaeText.getText().toString());
    }

    private final static String fileName = "medicine.json";

    /**
     * 解析药物信息json、
     */
    public void setErweimaMessage() {
        String files = AppJsonFileReader.readLocalJson(PageActivity.this, fileName);
        MedicinesBean medicinesBean = JSON.parseObject(files, MedicinesBean.class);

        List<Medicines> medicines = medicinesBean.getJuchengesp().getMedicines();
        AppJsonFileReader.createData(medicines, UserMessage.drug_Message_Map);

    }

    /**
     * 清空所有信息
     */
    public void ClearMessage() {

        //清空所有缓存信息
        datas.removeData(MyGlobal1.ALLBIAODANMESSAGE);
        datas.removeData(MyGlobal1.NURSE_NAME);
        //主页个人信息清空
        nurseNamaeText.setText("");
        nameText.setText("");
        sexText.setText("");
        ageText.setText("");
        hospitalNumberText.setText("");
        bedNumberText.setText("");
        officeText.setText("");
        allergiesText.setText("");
        diagnoseText.setText("");
        EventBus.getDefault().post(new MessageEvent("", 2));
    }

    // TODO MHandler
    private class MHandler extends Handler {
        private WeakReference<PageActivity> mActivity;

        public MHandler(PageActivity activity) {
            mActivity = new WeakReference<PageActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            PageActivity theActivity = mActivity.get();
            switch (msg.what) {
                case MyGlobal.MSG_WORKTHREAD_SEND_CONNECTBTRESULT: {
                    int result = msg.arg1;
                    if (1 == result) {// 连接成功记录最后一次连接成功记录
                        Bundle data = msg.getData();
                        String connectedBTName = data.getString(MyGlobal.STRPARA2);
                    }
                    break;
                }
                case MyGlobal.MSG_WORKTHREAD_SEND_CONNECTNETRESULT: {
                    int result = msg.arg1;
                    if (1 == result) {// 连接成功记录最后一次连接成功记录
                        Bundle data = msg.getData();
                        String connectedIPAddress = data
                                .getString(MyGlobal.STRPARA1);
                    }
                    break;
                }
                case MyGlobal.MSG_WORKTHREAD_SEND_CONNECTUSBRESULT: {
                    int result = msg.arg1;
                    if (1 == result) {// 连接成功记录最后一次连接成功记录
                    }
                    break;
                }
                case MyGlobal.MSG_WORKTHREAD_SEND_STATECHANGED: {
                    String type = WorkService.workThread.getText();
                    if (type.contains("正在连接")) {
                        theActivity.connect.setImageResource(R.drawable.btn_ljzt_n);
                        theActivity.connectText.setText(type);
                    } else if (type.contains("连接到")) {
                        theActivity.connect.setImageResource(R.drawable.btn_ljzt_p);
                        theActivity.connectText.setText("已连接");
                    } else if (type.contains("没有连接")) {
                        theActivity.connect.setImageResource(R.drawable.btn_ljzt_n);
                        theActivity.connectText.setText("未连接");
                    }
                    break;
                }
                case MyGlobal.CMD_WRITERESULT:
                    theActivity.connect.setImageResource(R.drawable.btn_ljzt_p);
                    theActivity.connectText.setText("已连接");
                    break;
                default:
                    theActivity.connect.setImageResource(R.drawable.btn_ljzt_n);
                    theActivity.connectText.setText("未连接");
                    break;
            }
        }
    }

    /**
     * 设置页码
     */
    public static void setPageNumber(String number) {
        pageNumberAction.setText(number);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        WorkService.delHandler(mHandler);
        mHandler = null;
    }
}
